from django.http import JsonResponse
from rest_framework.views import APIView
from app01 import models
from django import forms
from app01.models import Ap2Info
from app01.woutils.user_jwt import ParseToekn

class HttpCode(object):
    '''
    定义状态
    '''
    ok = 200
    paramserror = 400
    unauth = 401
    methoderror = 405
    servererror = 500


class Ap2InfoForm(forms.ModelForm):
    
    class Meta:
        model = Ap2Info
        fields = '__all__'


class Ap2_api(APIView):
    #接口
    def get(self, request, code=HttpCode.ok, kwargs=None):
        #获取页数参数
        try:
            page=int(request.query_params["page"])          #获取get请求传递的参数 page
            pagesize =int(request.query_params["pagesize"])
        except Exception as e:
            page = 1
            pagesize = 10
        if page < 1 :
            page = 1


        dic = {}
        username=request.query_params.get("username","")
        claid=request.query_params.get("claid","")
        phone=request.query_params.get("phone","")
        remark=request.query_params.get("remark","")
        statu =request.query_params.get("statu","")
        project =request.query_params.get("project","")
        if username:
            dic['username__icontains'] = username    #username是需要搜索的字段名 __icontains为使用模糊搜索
        if claid:
            dic['claid__icontains'] = claid
        if phone:
            dic['phone__icontains'] = phone
        if statu:
            dic['statu'] = statu
        if project:
            dic['project__icontains'] = project

        token = request.META.get('HTTP_AUTHORIZATION')  # 获取token
        token_dic, err = ParseToekn(token)

        # 管理员可以看所有人的
        if token_dic['data']['level'] == 10:
            pass
        else:
            #普通用户只能看自己的
            dic['account'] = token_dic['data']['username']
        #计算分页值
        #计算每一页显示内容的范围
        start_page = page * pagesize -pagesize           
        end_page = page * pagesize
      
        #查询数据库 获取数据        .order_by('-id')是按id倒序进行排列
        datas = models.Ap2Info.objects.filter(**dic).select_related('phone').order_by('-id')[start_page:end_page].values()   #从数据库中提取数据
        
        result = []
        for item in datas:
            item['CreatedTime'] = item['CreatedTime'].strftime("%Y-%m-%d %H:%M:%S")
            item['UpdatedTime'] = item['UpdatedTime'].strftime("%Y-%m-%d %H:%M:%S")
            # print(i['phone'])
            result.append(item)
        #查询总数据条数
        total = models.Ap2Info.objects.filter(**dic).count()
        json_dic = {
            'code': code, 
            'msg': '查询完成', 
            'data': {
                "data":result,
                "total":total
            }
        }
        if kwargs and isinstance(kwargs, dict) and kwargs.keys():
            json_dic.update(kwargs)
        return JsonResponse(json_dic, safe=False, json_dumps_params={'ensure_ascii': False})
        #制作返回给前端的json
        # data = {
        #     "code": 200,
        #     "msg": "查询成功",
        #     "data": {
        #         "data":result,
        #         "total":total
                
        #     }
        # }
        # return JsonResponse(data)          #以json格式返回数据
       


    def delete(self,request):
        '''删除数据'''
        #获取需要删除的id
        ids = request.query_params.get("id","")
        if ids == "":
            data = {'code': 503,"msg":"删除参数为空", 'data':""}
            return JsonResponse(data)
        #将字符串切割为列表
        ids = ids.split(",")
        ids_int = []
        for i in ids:
            if i == "":
                continue
            ids_int.append(int(i))  #将id转换为数字类型 然后添加到新的列表中

        #id__in为 根据id字段 传入一个列表 批量查询需要删除的数据
        Obj=models.Ap2Info.objects.filter(id__in=ids_int)
        #检测数据是否存在
        if not Obj.exists():
            data = {'code': 503, "msg": "未找到数据", 'data': ""}
            return JsonResponse(data)
        #删除查询到的数据
        Obj.delete()
        data = {'code': 200, "msg": "删除成功", 'data': ""}
        return JsonResponse(data)


    def post(self, request):

        #添加写入数据的用户信息
        token = request.META.get('HTTP_AUTHORIZATION')  # 获取token
        token_dic, err = ParseToekn(token)
        request.data['account'] = token_dic['data']['username']
        form = Ap2InfoForm(request.data)
        if form.is_valid():
            form.save()
            data = {'code': 200, "msg": "新增成功", 'data': ""}
        else:
            data = {'code': 503, "msg": "新增失败", 'data': form.errors}
        return JsonResponse(data)

    def put(self, request):
        uid = request.data.get("id")

        form = Ap2InfoForm(request.data, instance=Ap2Info.objects.get(pk=uid))
        if form.is_valid():
            form.save()
            data = {'code': 200, "msg": "修改成功", 'data': "修改成功"}
        else:
            data = {'code': 503, "msg": "数据不存在修改失败", 'data': "数据不存在修改失败"}
        return JsonResponse(data)

#下拉选择框数据获取
class Ap2_select_api(APIView):
    def get(self,request):
        datas=models.Iphoneinfo.objects.all().values()
        result = [i['phono'] for i in datas]
        data = {
            "code": 200,
            "msg": "查询成功",
            "data": result
        }
        return JsonResponse(data)